const express = require('express')
const { readCategoryList } = require('../../model/mongo')
const router = express.Router()

router.get('/getAll', async (req, res) => {
    const result = {
        code: 200,
        msg: '获取分类列表',
        data: ['error']
    }
    try {
        result.data = await readCategoryList()
        result.hashMap = groupByDesc(result.data.sort((next, pre) => {
            return next.localeCompare(pre)
        }))
    } catch (err) {
        result.code = 400
        result.msg = err + '原因未知'
    }
    res.send(JSON.stringify(result))
})

function groupByDesc(arr) {
    const [...zhCN] = '阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫杂'
    const [...EN] = 'abcdefghijklmnopqrstuvwxyz'
    const [...desc] = 'abcdefghjklmnopqrstwxyz'
    const isChinese = /[\u4e00-\u9fa5]+/
    const isSpecial = /^[0-9*#@!%$]+/
    const hashMap = {}

    function findIndex(obj) {
        for (let i = 0; i < isChinese.test(obj) ? zhCN.length : EN.length; i++) {
            if (obj.localeCompare(isChinese.test(obj) ? zhCN[i] : EN[i]) <= 0) {
                return i >= 1 ? i - 1 : 0
            }
        }
        return 22
    }

    arr.forEach(item => {
        let hashCode = isChinese.test(item) ? desc[findIndex(item)] : EN[findIndex(item)]
        isSpecial.test(item) ? hashCode = '#' : hashCode = hashCode
        if (!hashMap[hashCode]) {
            hashMap[hashCode] = []
        }
        hashMap[hashCode].push(item)
    })
    return hashMap
}

module.exports = router
